home *** CD-ROM | disk | FTP | other *** search
/ MacHack 2000 / MacHack 2000.toast / pc / The Hacks / MacHacksBug / Python 1.5.2c1 / Extensions / img / Lib / imgpxxx.py < prev    next >
Encoding:
Python Source  |  2000-06-23  |  1.4 KB  |  68 lines

  1. "Template for image file reader/writers in Python"
  2. #
  3. # Generic image reader/writer module, python version
  4. #
  5. from imgformat import error
  6.  
  7. class reader:
  8.     "Object that reads the image."
  9.     
  10.     def __init__(self, file):
  11.         """Initialize. You should read the header and fill in attributes
  12.         such as width, height, format_choices, format and colormap"""
  13.         
  14.         if type(file) == type(''):
  15.             self._filename = file
  16.             self._fp = open(file, 'rb')
  17.         else:
  18.             self._filename = '<open file>'
  19.             self._fp = file
  20.         self.width = 0
  21.         self.height = 0
  22.  
  23.     def args(self):
  24.         return self.__dict__
  25.         
  26.     def read(self):
  27.         "Read the image data"
  28.         
  29.         return ''
  30.  
  31.     def write(self, data):
  32.         raise error, 'Cannot write() to reader'
  33.  
  34. class writer:
  35.     "Object that writes to an image file"
  36.     
  37.     def __init__(self, file):
  38.         if type(file) == type(''):
  39.             self._filename = file
  40.             self._fp = None
  41.         else:
  42.             self._filename = '<open file>'
  43.             self._fp = file
  44.  
  45.     def args(self):
  46.         return self.__dict__
  47.         
  48.     def _get(self, attr):
  49.         try:
  50.             return getattr(self, attr)
  51.         except AttributeError:
  52.             raise error, "Required attribute '%s' missing"%attr
  53.  
  54.     def read(self):
  55.         raise error, 'Cannot read() from writer'
  56.  
  57.  
  58.     def write(self, data):
  59.         """Write the image file, according to attribute format"""
  60.         
  61.         w = self._get('width')
  62.         h = self._get('height')
  63.         if w*h != len(data):
  64.             raise error, 'Incorrect datasize'
  65.         if not self._fp:
  66.             self._fp = open(self._filename, 'wb')
  67.             
  68.